import 'package:bruno/bruno.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:interrogation/src/module/chat/widgets/base_message_card.dart';

import '../../../../data/models/char_record_res.dart';
import '../controllers/chat_detail_page_controller.dart';

class ChatDetailPageView extends GetView<ChatDetailPageController> {
  const ChatDetailPageView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xffF1F1F1),
      appBar: BrnAppBar(
        automaticallyImplyLeading: true,
        title: controller.receiverName,
        backgroundColor: const Color(0xffF1F1F1),
        showDefaultBottom: true,
        backLeadCallback: () => Get.back(),
      ),
      body: Column(
        children: [
          Expanded(
            child: Obx(() => EasyRefresh(
              controller: controller.refreshController,
              header: const ClassicHeader(),
              footer: const ClassicFooter(),
              onLoad: controller.onLoad,
            //  onRefresh: controller.onRefresh,
              child: ListView.builder(
                reverse: true,
                shrinkWrap: true,
               //   physics: NeverScrollableScrollPhysics(),
                padding: const EdgeInsets.symmetric(vertical: 8),
                itemCount: controller.list.length,
                itemBuilder: (context, index) {
                  if (index >= controller.list.length) return null;
                  return _buildItem(controller.list[index]);
                },
              ),
            )),
          ),
          Material(
            elevation: 4,
            shadowColor: Colors.black.withOpacity(0.1),
            child: Container(
              height: 68,
              color: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: controller.textEditingController,
                      focusNode: controller.focusNode,
                      decoration: InputDecoration(
                        filled: true,
                        fillColor: Colors.grey[200],
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12),
                          borderSide: BorderSide.none,
                        ),
                        hintText: '输入消息...',
                        hintStyle: const TextStyle(color: Colors.grey),
                        contentPadding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  ElevatedButton.icon(
                    onPressed: controller.sendMsg,
                    icon: const Icon(Icons.send, color: Colors.white),
                    label: const Text(
                      '发送',
                      style: TextStyle(color: Color(0xff1B1B48), fontSize: 14),
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.cyan,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildItem(ChatMessage model) {
    bool isUser = model.senderId == controller.senderId;
    String defaultAvatar = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.qOVNXup8kQ0DZg7RTVN3ZwHaE8?w=259&h=211&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2';
    
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0,horizontal: 8),
      child: Row(
        mainAxisAlignment: isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isUser) _buildAvatar(controller.receiverAvatar ?? ""),
          Flexible(
            child: BaseAskMsgCard(
              role: isUser ? 0: 1,
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                child: Text(
                  model.messageContent ?? '',
                  style: TextStyle(
                    color: isUser ? Colors.white : Colors.black87,
                    fontSize: 16,
                  ),
                ),
              ),
            ),
          ),
          if (isUser) _buildAvatar(controller.senderAvatar ?? ""),
        ],
      ),
    );
  }

  Widget _buildAvatar(String avatarUrl) {
    return Container(
      height: 36,
      width: 36,
      margin: EdgeInsets.only(left: 4,right: 4,top: 8),
      child: CachedNetworkImage(
        imageUrl: avatarUrl,
        imageBuilder: (context, image) => CircleAvatar(
          foregroundImage: image,
          radius: 18,
        ),
        errorWidget: (context, url, error) => Container(
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.5),
            borderRadius: BorderRadius.circular(18),
          ),
        ),
        placeholder: (context, url) => Container(
          decoration: BoxDecoration(
            color: const Color(0xffF1F1F1),
            borderRadius: BorderRadius.circular(18),
          ),
        ),
      ),
    );
  }
}
